package laveleria;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class LaVeleria {

	private static Map<String, String> mapa = null;
	private static final String LA_VELERIA = "laveleria.la_veleria";
	private static final String DATOS_ENTRADA = "datosEntrada";
	private static final String REFRESH = "{refresh}";
	private static final String TITULO = "{titulo}";
	private static String[] ultimaFilaDatosClima = null;

	public LaVeleria() {
		mapa = new HashMap<String, String>();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			mapa = armarHashMap();
			reemplazarEnTemplate(getMessage("template"), mapa);
		} catch (Exception ioe) {
			System.err.println(ioe.toString());
		}
	}

	private static void cargarDatosClima() throws Exception {
		ReverseFileReader reverseFileReader = new ReverseFileReader(
				getMessage(DATOS_ENTRADA));
		String ultimaFila = reverseFileReader.readLine();
		ultimaFilaDatosClima = ultimaFila.split(",");
	}

	private static String recuperarUltimoDatoClima(String indice) {
		// recuperar de DATOS_ENTRADA la columna indice y devolver el valor.
		return "dato";
	}

	private static Map<String, String> armarHashMap() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put(REFRESH, getMessage(REFRESH));
		map.put(TITULO, getMessage(TITULO));

		cargarDatosClima();
		ResourceBundle rb = ResourceBundle.getBundle(LA_VELERIA);
		Enumeration<String> enumeration = rb.getKeys();
		while (enumeration.hasMoreElements()) {
			String elem = enumeration.nextElement();
			if (elem.startsWith("indice")) {
				String key = elem.substring(6);
				map.put(key, recuperarUltimoDatoClima(getMessage(elem)));
			}
		}

		return map;
	}

	private static String reemplazarEnHtml(String htmlLine) {
		String line = htmlLine;
		for (Map.Entry<String, String> e : mapa.entrySet()) {
			System.out.println(e.getKey() + "," + e.getValue());
			line = line.replace(e.getKey(), e.getValue());
		}

		return line;
	}

	private static void reemplazarEnTemplate(String fileName,
			Map<String, String> hashMap) throws IOException {
		BufferedReader in = null;
		try {
			File file = new File(fileName);
			FileOutputStream out = new FileOutputStream(getMessage("output"));
			in = new BufferedReader(new FileReader(file));
			String line;
			String html = "";
			// Leo linea por linea el archivo y voy reemplazando con lo del
			// HashMap.
			while ((line = in.readLine()) != null) {
				html = html + reemplazarEnHtml(line) + "\n";
			}
			// Finished reading file, close it up.
			out.write(html.getBytes());
		} catch (IOException e) {
			System.out.println("error de lectura: " + e.getMessage());
		} finally {
			in.close();
		}

	}

	public static String getMessage(String property) {
		String message = null;
		ResourceBundle rb = ResourceBundle.getBundle(LA_VELERIA);
		message = rb.getString(property).trim();
		System.out.println(message);
		return message;
	}

	/*
	 * public static void xmlToHtml(HttpServletRequest request,
	 * HttpServletResponse response, String xmlS, String xsl) { PrintWriter out =
	 * null; //returns HTML. response.setContentType("text/html");
	 * 
	 * //get the real path for xml and xsl files.
	 * 
	 * String ctx = request.getSession().getServletContext().getRealPath("xsl");
	 * try { //Output goes in the response stream. out = response.getWriter();
	 * TransformerFactory tFactory = TransformerFactory.newInstance();
	 * 
	 * //Get the XML input document and the stylesheet. Source xmlSource = new
	 * StreamSource(new StringReader(xmlS)); Source xslSource = new
	 * StreamSource(new URL("file", "", ctx + "/" + xsl).openStream());
	 * 
	 * //Generate the transformer. xslSource.setSystemId(ctx + "\\");
	 * 
	 * Transformer transformer = tFactory.newTransformer(xslSource);
	 * 
	 * transformer.transform(xmlSource, new StreamResult(out)); } catch
	 * (Exception e) { armarError("Inesperado", e.toString(), request); String
	 * error = "<TABLE width='90%' cellSpacing='0' cellPadding='2' border='0'
	 * align='center' class='cuadrado fondoCeleste'><tr><td class='rojoAdvertencia'>" +
	 * e.toString() + "</td></tr></TABLE>"; out.println(error); }
	 * out.flush(); }
	 */
}
